package com.isae.chattingapp;

import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Presence;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

public class Login extends AsyncTask<Void,Void,XMPPConnection > {
	
	private Context LoginContext;
	private XMPPConnection ConnectionLogin;
    
    CallbackConnect callback;
    private static String USERNAME;
    private static String PASSWORD;
    private ProgressDialog dialog;
    
    public Login(CallbackConnect callback, Context ctx, String username, String password){
    	this.callback = callback;
    	this.LoginContext = ctx;
    	Login.USERNAME = username;
    	Login.PASSWORD = password;
    	this.ConnectionLogin = XMPPLogic.getInstance().getConnection();
    	
    }
    
    @Override
    protected void onPreExecute() {
    	dialog = new ProgressDialog(LoginContext);
    	dialog.setMessage("Logging...");
        dialog.setTitle("Please wait...");
        dialog.setIndeterminate(true);
        dialog.setCancelable(false);
        dialog.show();
    }	  

	@Override
	protected XMPPConnection doInBackground(Void... params) {
		try {
   		 ConnectionLogin.login(USERNAME, PASSWORD);
	     Log.i("XMPPChatDemoActivity",  "Logged in as" + ConnectionLogin.getUser());
	
	    } catch (XMPPException ex) {
	          Log.e("XMPPChatDemoActivity", "Failed to log in as "+  USERNAME);
              Log.e("XMPPChatDemoActivity", ex.toString());
	    }      
		return ConnectionLogin;
	}
	
	@Override
	protected void onPostExecute(XMPPConnection ConnectionLogin) {
		dialog.dismiss();
		callback.run(ConnectionLogin);
	}    

}
